<template>
  <div></div>
</template>
<script lang="js">
import { defineComponent } from 'vue'
import Store from '@/store'
import { useRoute } from 'vue-router'
import router from '@/router'
import { WxAuthConfig, ProjectConfig } from "@/config";

const getMyParams = () => {
  // 将search字符串转为对象
  function searchObj(search) {
    return JSON.parse("{\"".concat(decodeURIComponent(search.substring(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"'), "\"}"));
  }
  if (useRoute().query.sessionId) {
    console.log('-----useRoute-----', useRoute().query)
    return useRoute().query;
  } else if (location.search) {
    console.log('-----search-----', location.search)
    const search = searchObj(location.search)
    return search;
  }
  return {}
}

export default defineComponent({
  name: 'Login',
  setup() {
    const isDev = process.env.NODE_ENV === 'development';
    if (isDev) {
      const testUser = WxAuthConfig.getTestUser();
      Store.commit('setUser', testUser);
      router.replace({
        path: '/'
      })
    } else {
      if (Store.getters.isLogin) {
        // @ts-ignore
        WeixinJSBridge.call('closeWindow');
      } else {
        const params = getMyParams();
        console.log('-----getMyParams-----', params)
        if (params.sessionId && params.userId && params.openId) {
          Store.commit('setUser', {
            userId: params.userId,
            sessionId: params.sessionId,
            openId: params.openId
          })
          router.push({
            path: '/home'
          })
        } else {
          const loginPageUrl = WxAuthConfig.loginPageBaseUrl;
          const redirectUri = encodeURIComponent(WxAuthConfig.redirectUri);

          const authUrl = loginPageUrl + '&source=vue&returnUrl=' + redirectUri;
          setTimeout(() => {
            window.location.replace(authUrl);
          })
        }
      }
    }
    return {
    };
  }
})

</script>
<style>
</style>
